/**
 * 批量批量导入外网户型、方案、样板间到内网
 * */


const eachLimit = require('async/eachLimit');
const logUtil = require('../utils/log_util');
const projectJsonCrtl = require('./project_json_ctrl');
const squel = require('squel');
const mySqlutil = require('../utils/mysql_util');
const request = require('request');
const downloadImage = require('../utils/downloadByUrl');
const gridFSBuckets = require('../mongod/gridFSBuckets');
const fs = require('fs');
const path = require('path');
const uuid4 = require('uuid/v4');

/**
 * 根据输入方案（户型）数据，构建方案（户型）实体对象
 * @param designMap
 * @param userId
 * @returns {{}}
 */
const createDesign = (designMap) => {
  const design = {};
  if (designMap) {
    // 用户信息
    if (designMap.userId) {
      design.user_id = designMap.userId;
    }
    if (designMap.login) {
      design.user_login = designMap.login;
    }
    if (designMap.vendorCode) {
      design.vendor_code = designMap.vendorCode;
    }
    if (designMap.agencyId) {
      design.agency_id = designMap.agencyId;
    }
    // 户型编码
    if (designMap.designId) {
      design.designId = designMap.designId;
    } else {
      design.designId = uuid4();
    }
    if (designMap.sourceId) {
      design.source_designId = designMap.sourceId;
    }
    // 方案类型  2 方案 3 样板间  4户型
    if (designMap.assetType) {
      design.asset_type = parseInt(designMap.assetType, 10);
    }
    // 户型背景底图
    if (designMap.backgroundImage) {
      design.background_image = designMap.backgroundImage;
    }
    if (designMap.area && !isNaN(parseFloat(designMap.area))) {
      design.area = designMap.area;
    }
    // 户型描述
    if (designMap.data) {
      if (designMap.data.totalarea) {
        // 户型背景底图
        design.total_area = parseFloat(designMap.data.totalarea).toFixed(2);
        if (!design.area) {
          design.area = design.total_area;
        }
      }
      if (designMap.data.thumbnail3dTopCam) {
        // 取出户型或方案辅助数据，下一步需要保存到Mysql，方案基本信息表
        design.thumbnail3d_top_cam = designMap.data.thumbnail3dTopCam;
      }
    }

    // 取出户型数据，如户型所属省市区、小区，以及户型大小等
    // 户型名称
    if (designMap.name) {
      design.name = designMap.name;
    }
    if (designMap.space) {
      design.space = designMap.space;
    }
    if (designMap.bedrooms) {
      design.bedrooms = designMap.bedrooms;
    }
    if (designMap.livingRooms) {
      design.living_rooms = designMap.livingRooms;
    }
    if (designMap.restrooms) {
      design.restrooms = designMap.restrooms;
    }

    if (designMap.realArea && !isNaN(parseFloat(designMap.realArea))) {
      design.real_area = designMap.realArea;
    }
    if (designMap.style) {
      design.style = designMap.style;
    }
    if (designMap.description) {
      design.description = designMap.description;
    }
    if (designMap.province) {
      if (designMap.province.text) {
        design.province = designMap.province.text;
      }
      if (designMap.province.code) {
        design.province_code = designMap.province.code;
      }
    }
    if (designMap.city) {
      if (designMap.city.text) {
        design.city = designMap.city.text;
      }
      if (designMap.city.code) {
        design.city_code = designMap.city.code;
      }
    }
    if (designMap.district) {
      if (designMap.district.text) {
        design.district = designMap.district.text;
      }
      if (designMap.district.code) {
        design.district_code = designMap.district.code;
      }
    }
    if (designMap.neighbor) {
      design.neighbor = designMap.neighbor;
    }

    if (designMap.sharedBrand) {
      design.shared_brand = designMap.sharedBrand;
    }

    if (designMap.gmtCreate) {
      design.gmt_Create = designMap.gmtCreate;
    }
  }
  return design;
};


/**
 * 执行方案（户型）保存操作
 * @param designMap
 * @param userId
 */
const exectSaveDesign = (designMap) => {
  // 构建方案（户型）对象
  const design = createDesign(designMap);

  let strImage;
  let strTopImage;
  // 取出户型方案的Json数据
  const strData = designMap.data.data;

  return new Promise((res, rej) => {
    Promise.all([downloadImage.getBase64BitDataByUrl(designMap.data.image),
      downloadImage.getBase64BitDataByUrl(designMap.data.top3DImage)
    ]).then((results) => {
      strImage = results[0];
      strTopImage = results[1];
      if (!strImage && designMap.data.thumbnail3d)strImage = designMap.data.thumbnail3d;
      if (strImage) strImage = strImage.replace(/^data:image\/\w+;base64,/, '');
      if (strTopImage) strTopImage = strTopImage.replace(/^data:image\/\w+;base64,/, '');
      Promise.all([projectJsonCrtl.saveDesignJson(strData, design.designId, design.user_id),
        gridFSBuckets.save(strImage, `${design.designId}_jt.jpg`, 'project_image', false),
        gridFSBuckets.save(strTopImage, `${design.designId}_top3D.jpg`, 'project_image', false),
        mySqlutil.execute(squel.delete().from('project').where('designId = ?', design.designId).toString())
      ]).then(() => {
        const sql = squel.insert().into('project').setFields(design).toString();
        mySqlutil.execute(sql).then(() => {
          res(design);
        }).catch((err) => {
          logUtil.error(err);
          rej(err);
        });
      }).catch((err) => {
        logUtil.error(err);
        rej(err);
      });
    }).catch((err) => {
      rej(err);
    });
  });
};


// 用户登录
const userLoginData = { userId: 'ccp', password: 'ccp123456' };
const userLogin = () => new Promise((res, rej) => {
  request.post({ url: 'http://jiaeda.com/user/login', form: userLoginData },
    (err, httpResponse, body) => {
      if (err) console.error(err);
      const data = JSON.parse(body);
      if (data.status === 0) {
        res({ Accept: '*/*',
          'Content-Type': 'application/json;charset=UTF-8',
          'Accept-Encoding': 'gzip, deflate',
          'Accept-Language': 'zh-CN,zh;q=0.8',
          Connection: 'keep-alive',
          Cookie: httpResponse.headers['set-cookie']
        });
      } else {
        console.log(data.msg);
        rej();
      }
    });
});

/**
 * 递归遍历文件夹，取出JSON文件解析
 * @param filePath
 * @returns {*}
 */
const ergodicDesignIdUrl = designIds => new Promise((res, rej) => {
  userLogin().then((headers) => {
    // 异步，一次执行10个
    eachLimit(designIds, 10, (designid, callback) => {
      designid = designid.toString().trim();
      request({
        uri: `http://jiaeda.com/project/open?d=${designid}`,  // 构建请求
        headers
      }, (error, response, body) => {
        if (error) setImmediate(callback);
        const homeInfo = JSON.parse(body).data;
        // 判断是否存在方案数据体
        if (homeInfo && homeInfo.data) {
          if (!homeInfo.designId) { homeInfo.designId = uuid4(); }
          // 保存方案信息
          exectSaveDesign(homeInfo)
            .then((result) => { setImmediate(callback); })
            .catch((err) => {
              logUtil.error(err);
              setImmediate(callback);
            });
        } else {
          logUtil.error(`方案：${designid} 数据有问题！`);
          setImmediate(callback);
        }
      });
    });
  }).catch((err) => {
    logUtil.error(err);
    rej(err);
  });
});
/**
 * 根据方案Id，批量导入外网户型、方案、样板间数据到测试环境
 * @param designIds
 * @returns {Promise.<void>}
 */
exports.batchInputOuterProjectByDesignIds = async (designIds) => {
  try {
    await ergodicDesignIdUrl(designIds);
    // ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};


const ergodicFileJson = dataPath => new Promise((res, rej) => {
  fs.readdir(dataPath, (err, files) => {
    if (err) {
      console.log(err);
      rej(err);
    }
    // 异步，一次执行10个
    eachLimit(files, 10, (filename, callback) => {
      const filePath = path.join(dataPath, filename);
      fs.stat(filePath, (err1, stats) => {
        if (err1) {
          // 如果报错，则继续循环下一个
          logUtil.info(`error:${filePath}`);
          setImmediate(callback);
        }
        try {
          if (stats && stats.isFile()) { // 是文件
            if (path.extname(filePath) === '.json') {
            // 分析JSON文件
              // 同步读JSON文件
              const fileData = fs.readFileSync(filePath, 'utf-8');

              const homeInfo = JSON.parse(fileData);
              // 判断是否存在方案数据体
              if (homeInfo && homeInfo.data) {
                // homeInfo.designId = uuid4();
                if (!homeInfo.designId) { homeInfo.designId = uuid4(); }
                // 保存方案信息
                exectSaveDesign(homeInfo)
                  .then((result) => {
                    fs.unlink(filePath, (err) => {
                      if (err) logUtil.error(err);
                      logUtil.info(homeInfo.name);
                      setImmediate(callback);
                    });
                  })
                  .catch((err) => {
                    logUtil.error(err);
                    setImmediate(callback);
                  });
              } else {
                logUtil.error(`文件：${filePath} 数据有问题！`);
                setImmediate(callback);
              }
            } else {
            // 如果为非Json文件，则给出错误信息
              logUtil.info(`not json:${filePath}`);
              setImmediate(callback);
            }
          } else {
          // 如果是文件夹，则递归调用本函数
            ergodicFileJson(filePath);
            setImmediate(callback);
          }
        } catch (err2) {
          logUtil.error(err2);
        // 如果报错，则继续循环下一个
          logUtil.info(`error:${filePath}`);
          setImmediate(callback);
        }
      });
    });
  });
});

/**
 * 批量导入project数据
 * @param pathName
 * @returns {Promise.<void>}
 */
exports.batchInputProjectByJson = async (pathName) => {
  try {
    await ergodicFileJson(pathName);
    // ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};

